package com.niit.project.dao.impl;

import com.niit.project.dao.BadGoodsDao;
import com.niit.project.entity.BadGoods;
import com.niit.project.entity.Page;
import com.niit.project.utils.Dbutils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

public class BadGoodsDaoImpl implements BadGoodsDao {
    QueryRunner queryRunner = new QueryRunner();
    @Override
    public List<BadGoods> selectAll(Page page) {
        try {
            //分页查询方法的实现
            List<BadGoods> badGoods = queryRunner.query(Dbutils.getConnection(),"select * from badgoods limit ?,?",new BeanListHandler<BadGoods>(BadGoods.class),page.getStartRows(),page.getPageSize());
            return badGoods;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public long selectCount() {
        try {
            long count = (long) queryRunner.query(Dbutils.getConnection(),"select count(*) from badgoods",new ScalarHandler());
            return count;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int delete(int id) {
        try {
            int result = queryRunner.update(Dbutils.getConnection(),"delete from badgoods where id = ?",id);
            return result;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int insert(BadGoods badGoods) {
        try {
            int result = queryRunner.update(Dbutils.getConnection(),"insert into badgoods (username,goodname,goodtype,changemedium,changeway) values(?,?,?,?,?)",badGoods.getUsername(),badGoods.getGoodname(),badGoods.getGoodtype(),badGoods.getChangemedium(),badGoods.getChangeway());
            return result;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public BadGoods select(int id) {
        try {
            BadGoods badGoods= queryRunner.query(Dbutils.getConnection(),"select * from badgoods where id = ?",new BeanHandler<BadGoods>(BadGoods.class),id);
            return badGoods;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

}
